<template>
  <div>
    <!-- 头部 -->
      <div class="frist_show">
          <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/physique/' +  uid}">专家咨询</el-breadcrumb-item>
          <el-breadcrumb-item>专家咨询聊天</el-breadcrumb-item>
          </el-breadcrumb>
          <el-divider></el-divider>
      </div>
    <!-- 聊天框 -->
    <JwChat-index
      :config='config'
      :taleList='beforeObj.consultMsg'
      @enter='bindEnter'
      v-model='inputMsg'
      :toolConfig='tool'
      @clickTalk='talkEvent'
      :winBarConfig="winBarConfig"
      class="jwchat_position"
    >
      <JwChat-talk class='rightSlot' :Talelist='talk' :config='quickConfig' @event='bindTalk' />
    </JwChat-index>

 <!-- 查看健康师详情 -->
    <el-dialog title="健康师信息" :visible.sync="dialogVisible" width="70%" >
      <el-descriptions title="查看健康师信息" direction="vertical" :column="4" border style="margin:10px">
        <el-descriptions-item label="姓名">{{watchDetails.hmName}}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{watchDetails.hmPhone}}</el-descriptions-item>
        <el-descriptions-item label="出生日期"><el-tag>{{watchDetails.hmBirthday}}</el-tag></el-descriptions-item>
        <el-descriptions-item label="年龄">{{watchDetails.hmAge}}</el-descriptions-item>
        <el-descriptions-item label="性别">{{watchDetails.hmGender}}</el-descriptions-item>
        <el-descriptions-item label="民族">{{watchDetails.hmNation}}</el-descriptions-item>
        <el-descriptions-item label="文化程度">{{watchDetails.hmDegree}}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{watchDetails.hmEmail}}</el-descriptions-item>
        <el-descriptions-item label="联系地址" :span="2">{{watchDetails.hmAddress}}</el-descriptions-item>
        <el-descriptions-item label="个人说明" :span="2">{{watchDetails.hmDesc}}</el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 发送图片的file -->
    <input id="imgFileQian" type="file" @change="fileUploadImage()" accept=".gif,.jpg,.jpeg,.png" v-show="false">
    <!-- 发送文件的file -->
    <input id="fieldFileQian" type="file" @change="fileUploadField()" v-show="false">
  </div>
</template>

<script>
export default {
  data () {
    return {
      userInfo: {},
      inputMsg: '',
      tool: {
        show: ['video', 'img', ['发送文件', '发送图片']],
        callback: this.toolEvent
      },
      quickConfig: {
        nav: ['快捷回复'],
        showAdd: false,
        maxlength: 200,
        showHeader: false,
        showDeleteBtn: false
      },
      talk: [
        '专家您好！',
        '体检的流程是什么？',
        '我的体检结果多久能出？',
        '健康干预是什么？',
        '我需要多久复诊一次？',
        '非常感谢!',
        '体检前应注意什么？'
      ],
      // 顶栏的展示
      config: {
        img: '',
        name: '',
        dept: '',
        memId: '',
        callback: this.bindCover
      },
      chatTableList: [], // 消息列表数组
      winBarConfig: {},
      loading: true, // 加载变量
      beforeObj: { consultMsg: [], chatTaId: null }, // 当前聊天对象
      activeWhereItem: 0, // 当前聊天对象总表ID
      watchDetails: {}, // 查看健康师详情
      dialogVisible: false, // 对话框变量
      timeOut: null, // 计时器变量
      uid: '',
      loading1: null
    }
  },
  methods: {
    // 点击聊天框中的信息时触发
    talkEvent (play) {
      // alert('点击聊天信息或者头像信息时触发' + play)
      if (play.data.mine === false) {
        if (play.type === 'img') {
          this.$axios.post(`/api/DHHealthManagerController/queryByIdHealth?hmId=${play.data.id}`).then(({data}) => {
            this.watchDetails = data
            this.dialogVisible = true
          })
        }
      } else if (play.data.mine === true) {
        if (play.type === 'img') {
          this.$message({
            showClose: true,
            message: '可以前往个人中心查看个人信息哦～',
            type: 'warning'
          })
        }
      }
    },
    // 发送消息
    bindEnter () {
      const msg = this.inputMsg
      if (!msg) return
      // alert('点击发送触发' + msg)
      this.$axios.post(`/api/manager/addConsultMsg?chatTaId=${this.beforeObj.chatTaId}&conMesType=0&conMesContent=${msg}&conMesState=${this.userInfo.memId}&conMesAccount=${this.userInfo.memPhone}`).then(result => {
        this.initChatTableList()
      })
    },
    // 打开发送文件和图片的方法
    toolEvent (type) {
      // alert('点击发送文件和图片触发')
      if (type === 'img') {
        document.getElementById('imgFileQian').click()
      } else if (type === 'video') {
        document.getElementById('fieldFileQian').click()
      }
    },
    // 查看聊天人信息
    bindCover (type) {
      // alert('点击顶栏个人信息时触发')
      this.$axios.post(`/api/DHHealthManagerController/queryByIdHealth?hmId=${type.value.hmId}`).then(({data}) => {
        this.watchDetails = data
        this.dialogVisible = true
      })
    },
    // 快捷回复
    bindTalk (play) {
      if (play.key === 'select') {
        // alert('发送快捷')
        this.$axios.post(`/api/DHChatTableController/addConsultMsg?chatTaId=${this.beforeObj.chatTaId}&conMesType=0&conMesContent=${play.value}&conMesState=${this.userInfo.memId}&conMesAccount=${this.userInfo.memPhone}`).then(result => {
          this.initChatTableList()
        })
      }
    },
    // 加载个人信息的方法
    initUserInfo () {
      let user = JSON.parse(sessionStorage.getItem('user'))
      this.userInfo = user
      this.initChatTableList()
      // 如果不为空先清除
      if (this.timeOut != null) {
        clearInterval(this.timeOut)
      }
      // 开启计时器
      this.timeOut = setInterval(() => {
        this.initChatTableList()
      }, 3000)
    },
    // 加载消息列表的方法
    initChatTableList () {
      this.$axios.post(`/api/CXKChatTableController/initChatTableList?memId=${this.userInfo.memId}`).then(({data}) => {
        let winBarConfig = {
          active: '',
          width: '180px',
          listHeight: '65px',
          list: [],
          callback: this.bindWinBar
        }
        if (this.activeWhereItem === 0) {
          this.activeWhereItem = data[0].chatTaId
        }
        winBarConfig.active = this.activeWhereItem
        data.forEach((e, i) => {
          let lastTime = ''
          if (e.messagesList.length === 0) {
            lastTime = '无咨询记录'
          } else {
            let time = e.messagesList[e.messagesList.length - 1].conMesTime
            let date = new Date(time)
            let month = date.getMonth() + 1
            let day = date.getDate()
            day = day < 10 ? '0' + day : day
            let hours = date.getHours()
            let minutes = date.getMinutes()
            minutes = minutes < 10 ? '0' + minutes : minutes
            time = month + '/' + day + ' ' + hours + ':' + minutes
            if (date.getFullYear() !== new Date().getFullYear()) {
              time = e.messagesList[e.messagesList.length - 1].conMesTime
            }
            lastTime = time
          }
          let obj = {
            id: e.healthManager.hmId,
            img: 'http://192.168.43.183/files/' + e.healthManager.hmImg,
            name: e.healthManager.hmName,
            dept: lastTime,
            readNum: e.noWatchCount,
            chatTaId: e.chatTaId
          }
          winBarConfig.list.push(obj)
        })
        this.winBarConfig = winBarConfig
        this.chatTableList = data
        this.loading = false

        // 循环聊天列表，拿到当前聊天的对象
        this.chatTableList.forEach(e => {
          if (this.activeWhereItem === e.chatTaId) {
            // 修改查看状态
            this.$axios.put(`/api/CXKChatTableController/upConsultHmWatch?chatTaId=${e.chatTaId}`).then(result => {
              this.initChatTableList()
            })
            this.beforeObj = e
            this.beforeObj.consultMsg = []
            this.config.img = 'http://192.168.43.183/files/' + e.healthManager.hmImg
            this.config.name = e.healthManager.hmName
            this.config.dept = '个人说明：' + e.healthManager.hmDesc
            this.config.hmId = e.healthManager.hmId
            // 循环聊天记录进行封装
            e.messagesList.forEach((con, i) => {
              let mine = false
              let name = ''
              let img = ''
              let text = ''
              let id = 0
              if (con.conMesState === e.hmId && con.conMesAccount === e.healthManager.hmUsername) {
                mine = false
                name = e.healthManager.hmName
                img = 'http://192.168.43.183/files/' + e.healthManager.hmImg
                id = e.healthManager.hmId
              } else {
                mine = true
                name = e.member.memName
                img = 'http://192.168.43.183/files/' + e.member.memImg
                id = e.member.memId
              }
              if (con.conMesType === 0) {
                text = con.conMesContent
              } else if (con.conMesType === 1) {
                text = '<img data-src="http://192.168.43.183/files/' + con.conMesContent + '"/>'
              } else if (con.conMesType === 2) {
                if (mine === true) {
                  text = '<a style="" href="http://192.168.43.183/files/' + con.conMesContent + '" target="_blank">发送文件，点击查看</a>'
                } else {
                  text = '<a style="color:red;" href="http://192.168.43.183/files/' + con.conMesContent + '" target="_blank">收到文件，点击查看</a>'
                }
              } else {
                text = con.conMesContent
              }
              let consult = {
                'date': con.conMesTime,
                'text': { 'text': text },
                'mine': mine,
                'name': name,
                'img': img,
                'id': id
              }
              this.beforeObj.consultMsg.push(consult)
            })
          }
        })
        this.loading1.close()
        // console.log(this.chatTableList)
      })
    },
    // 选择图片改变事件，进行发送
    fileUploadImage () {
      var files = document.getElementById('imgFileQian').files
      var params = new FormData()
      params.append('imgFileQian', files[0])
      this.$axios({
        url: `/api/CXKChatTableController/fileUploadImage?chatTaId=${this.beforeObj.chatTaId}&conMesType=1&conMesState=${this.userInfo.memId}&conMesAccount=${this.userInfo.memPhone}`,
        method: 'post',
        data: params,
        headers: { 'Content-Type': 'multipart/form-data' }
      }).then(result => {
        if (result.data) {
          this.initChatTableList()
          this.$message({
            message: '图片发送成功',
            type: 'success'
          })
        } else {
          this.$message.error('发送失败，出现未知错误，请稍后再试')
        }
      })
    },
    // 选择文件的改变事件，进行发送
    fileUploadField () {
      var files = document.getElementById('fieldFileQian').files
      var params = new FormData()
      params.append('fieldFileQian', files[0])
      this.$axios({
        url: `/api/CXKChatTableController/fileUploadField?chatTaId=${this.beforeObj.chatTaId}&conMesType=2&conMesState=${this.userInfo.memId}&conMesAccount=${this.userInfo.memPhone}`,
        method: 'post',
        data: params,
        headers: { 'Content-Type': 'multipart/form-data' }
      }).then(result => {
        if (result.data) {
          this.initChatTableList()
          this.$message({
            message: '文件发送成功',
            type: 'success'
          })
        } else {
          this.$message.error('文件发送失败，出现未知错误，请稍后再试')
        }
      })
    },
    // 点击列表的会员显示对话详情的方法
    bindWinBar (play = {}) {
      // console.log(play)
      this.activeWhereItem = play.data.chatTaId
    }
  },
  created () {
    const loading = this.$loading({
      lock: true,
      text: '正在努力加载',
      spinner: 'el-icon-loading',
      background: 'rgb(255, 255, 255)'
    })
    this.loading1 = loading
    this.initUserInfo()
    let men = sessionStorage.getItem('user')
    let meid = JSON.parse(men)
    this.uid = meid.memId
  }
}
</script>
<style>
.ChatPage .header[data-v-177d6428] {
    background-color: rgba(43, 193, 231, 0.911);
    width:750px;
    margin-top: 70px;
}
.wrapper .web__main .web__main-item--mine .web__main-text[data-v-08a2a04c] {
  background-color:rgba(43, 193, 231, 0.911);
}
.wrapper .web__main .web__main-item--mine .web__main-text .web__main-arrow[data-v-08a2a04c]:after {
  border-left-color: #00d8dac9;
}
.el-button--primary {
  color: #FFF;
  background-color: rgba(43, 193, 231, 0.911);
  border-color: rgba(43, 193, 231, 0.911)
}
.windowBar[data-v-5a0a6048] {
    background: rgba(239, 239, 243, 0.5);
    height: 100%;
    min-width: 150px;
    overflow: hidden;
    display: flex;
    border: 1px solid rgba(43, 193, 231, 0.911);
    border-bottom: none;
}
.windowBar .winItem[data-v-5a0a6048] {
  background: rgba(239, 239, 243, 0.5)
}
.windowBar .winItem[data-v-5a0a6048]:hover {
  background: rgba(219, 219, 224, 0.5)
}
.frist_show{position: absolute;top: 0px;left:20px;width: 1500px;height: 50px;}

.frist_show .el-breadcrumb{margin-top: 15px;}

</style>
